package com.microDynamic.service;

import com.alibaba.fastjson.JSONObject;
import com.microDynamic.service.biz.FolderSettings;
import com.microDynamic.service.biz.InsetTestCaseToExcel;
import com.microDynamic.service.biz.XMindToExcel;
import com.microDynamic.utils.FileExtension;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Service
public class XMindToExcelService {

    //获取文件绝对路径
    public final String uploadFolder =new FolderSettings().getUploadFolder();
    public final String downFolder =new FolderSettings().getDownFolder();
    private static Logger logger = LoggerFactory.getLogger(XMindToExcelService.class);

    /**
     * 查询xmind用例数
     * @param file
     * @return
     */
    public JSONObject getXmindFiles(MultipartFile file){
        JSONObject jsonObject=new JSONObject();
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 生成新的文件名，以防止文件名冲突+ FileExtension.XLSX
        String xmindFileName = extractPrefix(originalFilename);
        String  newXmindFilename =xmindFileName + "_" + UUID.randomUUID().toString()+FileExtension.XMIND;

        // 文件保存绝对路径
        String filePath = uploadFolder + newXmindFilename;
        // 保存文件到服务器
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        jsonObject.put("caseCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseNo());
        return jsonObject;
    }
    /**
     * Xmind源文件上传
     * @param templateType  模版类型：ones、MeterSphere
     * @param file  源文件
     * @return
     */
    public JSONObject importFile(String templateType, MultipartFile file){
        JSONObject jsonObject=new JSONObject();
        if (file.isEmpty()) {
            jsonObject.put("state",1);
            jsonObject.put("message", ResponseEntity.badRequest().body("请选择要上传的文件"));
            return jsonObject;
        }
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 生成新的文件名，以防止文件名冲突+ FileExtension.XLSX
            String xmindFileName = extractPrefix(originalFilename);
            String  newXmindFilename =xmindFileName + "_" + UUID.randomUUID().toString()+FileExtension.XMIND;

            // 文件保存绝对路径
            String filePath = uploadFolder + newXmindFilename;
            // 保存文件到服务器
            file.transferTo(new File(filePath));
            if(templateType.equals("ones")){
                logger.info("新文件名称：" + filePath);
                String excelFilePath= filePath.replaceAll(FileExtension.XMIND, FileExtension.XLSX);
                InsetTestCaseToExcel.setXMindFile(new File(filePath));
                InsetTestCaseToExcel.setExcelFilePath(excelFilePath);
                logger.info("文件保存路径：" + excelFilePath);
                InsetTestCaseToExcel.xMindToExcel(templateType);
                String fileName = extractPrefix(newXmindFilename)+ FileExtension.XLSX;
                jsonObject.put("data","fileName: " + fileName+","+"filePathUrl: " + uploadFolder +fileName);
                jsonObject.put("caseCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseNo());
                jsonObject.put("caseStepCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseSteps());
                jsonObject.put("verificationCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseCheckPointers());
                return jsonObject;
            }
            if(templateType.equals("MeterSphere")){
                logger.info("新文件名称：" + filePath);
                String excelFilePath= filePath.replaceAll(FileExtension.XMIND, FileExtension.XLSX);
                InsetTestCaseToExcel.setXMindFile(new File(filePath));
                InsetTestCaseToExcel.setExcelFilePath(excelFilePath);
                logger.info("文件保存路径：" + excelFilePath);
                InsetTestCaseToExcel.xMindToExcel(templateType);
                String fileName = extractPrefix(newXmindFilename)+ FileExtension.XLSX;
                jsonObject.put("data","fileName: " + fileName+","+"filePathUrl: " + uploadFolder +fileName);
                jsonObject.put("caseCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseNo());
                jsonObject.put("caseStepCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseSteps());
                jsonObject.put("verificationCount：", InsetTestCaseToExcel.testCaseInfo.getTestCaseCheckPointers());
            }
        } catch (Exception e) {
            jsonObject.put("state",1);
            jsonObject.put("message",ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage()));
            return jsonObject;
        }
        return jsonObject;
    }

    /**
     * EXcel文件下载
    // * @param templateType  模版类型：ones、MeterSphere
     * @param fileName  文件名称
     * @return
     */
    public ResponseEntity<byte[]> downloadFile(String fileName,String filePath,HttpServletRequest request) throws Exception {
        //创建该文件对象
        File file = new File(filePath + File.separator + fileName);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载方式打开(下载前对文件名进行转码)
        fileName=getFilename(request,fileName);
        headers.setContentDispositionFormData("attachment",fileName);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);} catch (Exception e) {e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),
                    HttpStatus.EXPECTATION_FAILED);
        }
    }

    //根据浏览器的不同进行编码设置，返回编码后的文件名
    private String getFilename(HttpServletRequest request, String filename)
            throws Exception {
        //IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        //获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示，并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
            }
        }
        //火狐等其他浏览器统一为ISO-8859-1编码显示
        return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
    }

    /**
     * 字符串处理
     * @param input
     * @return
     */
    public static String extractPrefix(String input) {
        int index = input.indexOf(".xmind");
        return input.substring(0, index);
    }
}
